package csc.fresher.finalgroupfour.filter;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import csc.fresher.finalgroupfour.domain.User;
import csc.fresher.finalgroupfour.service.UserService;

public class AuthentificationFailureListener implements
		AuthenticationFailureHandler {
	@Autowired
	private UserService userService;

	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException ae)
			throws IOException, ServletException {
		HttpSession session = request.getSession();
		String loginId = request.getParameter("loginId");
		User userLock = userService.findUser(loginId);
		if (userLock == null) {
			session.setAttribute("errorMessage", "Your account does not exist");
			response.sendRedirect("login?error=true");
		} else {
			userLock.setAttemptedLogin(userLock.getAttemptedLogin() + 1);
			userService.updateUser(userLock);

			session.setAttribute("errorMessage", "Invalid username or password");
			// user contains required data

			if (userLock.getAttemptedLogin() >= 3
					|| !userLock.getUserState().equalsIgnoreCase("enabled")) {
				userLock.setUserState("disabled");
				session.setAttribute("errorMessage",
						"Your account has been locked");
				userLock.setAttemptedLogin(0);
				userService.updateUser(userLock);
			}
			response.sendRedirect("login?error=true");
		}
	}
}